﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace Sharp
{
    public class ImgUtil
    {


        public static void GetEncoderParams(out ImageCodecInfo jpegCodec, out EncoderParameters encoderParams)
        {
            EncoderParameter qualityParam =
                          new EncoderParameter(Encoder.Quality, 90L);

            // Jpeg image codec
            jpegCodec =
                 getEncoderInfo("image/jpeg");

            encoderParams = new EncoderParameters(1);
            encoderParams.Param[0] = qualityParam;

        }

        private static void SaveHighQuality(string ImageSavePath, Bitmap bmpResized)
        {
            if (File.Exists(ImageSavePath))
                File.Delete(ImageSavePath);
            ImageCodecInfo jpegCodec;
            EncoderParameters encoderParams;
            GetEncoderParams(out jpegCodec, out encoderParams);
            bmpResized.Save(ImageSavePath, jpegCodec, encoderParams);
        }

        public static void ResizeFromStream(string ImageSavePath, int MaxSideSize, Stream Buffer)
        {
            int intNewWidth;
            int intNewHeight;
            Image imgInput = Image.FromStream(Buffer);

            //Determine image format
            ImageFormat fmtImageFormat = imgInput.RawFormat;

            //get image original width and height
            int intOldWidth = imgInput.Width;
            int intOldHeight = imgInput.Height;

            //determine if landscape or portrait
            int intMaxSide;

            if (intOldWidth >= intOldHeight)
            {
                intMaxSide = intOldWidth;
            }
            else
            {
                intMaxSide = intOldHeight;
            }

            if (intMaxSide > MaxSideSize)
            {
                //set new width and height
                double dblCoef = MaxSideSize / (double)intMaxSide;
                intNewWidth = Convert.ToInt32(dblCoef * intOldWidth);
                intNewHeight = Convert.ToInt32(dblCoef * intOldHeight);
            }
            else
            {
                intNewWidth = intOldWidth;
                intNewHeight = intOldHeight;
            }
            //create new bitmap
            Bitmap bmpResized = new Bitmap(imgInput, intNewWidth, intNewHeight);

            //save bitmap to disk


            SaveHighQuality(ImageSavePath, bmpResized);

            //release used resources
            imgInput.Dispose();
            bmpResized.Dispose();
            Buffer.Close();
        }


        public static void ResaveFromStream(string ImageSavePath)
        {
            Image imgInput = Image.FromFile(ImageSavePath, false);

            //Determine image format
            ImageFormat fmtImageFormat = imgInput.RawFormat;

            //create new bitmap with original dimensions
            Bitmap bmpResized = new Bitmap(imgInput, imgInput.Width, imgInput.Height);

            //save bitmap to disk
            //bmpResized.Save(ImageSavePath, fmtImageFormat);

            ImageCodecInfo jpegCodec;
            EncoderParameters encoderParams;
            GetEncoderParams(out jpegCodec, out encoderParams);

            String tempFile = ImageSavePath.Replace(".jpg", "-temp.jpg");

            SaveHighQuality(tempFile, bmpResized);

            //release used resources
            imgInput.Dispose();
            bmpResized.Dispose();

            //replace original
            if (File.Exists(ImageSavePath))
                File.Delete(ImageSavePath);
            File.Move(tempFile, ImageSavePath);
        }


        private static ImageCodecInfo getEncoderInfo(string mimeType)
        {
            // Get image codecs for all image formats
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();

            // Find the correct image codec
            for (int i = 0; i < codecs.Length; i++)
                if (codecs[i].MimeType == mimeType)
                    return codecs[i];
            return null;
        }


        public static void GetBiggestMask(string ImageSavePath, int height, double aspectRatio, String ImageOpenPath)
        {

            int Height = int.Parse(height.ToString());
            int Width = Convert.ToInt32((double)Height * aspectRatio);

            Image imgPhoto = Image.FromFile(ImageOpenPath, false);

            //Determine image format
            ImageFormat fmtImageFormat = imgPhoto.RawFormat;

            //get image original width and height
            int sourceWidth = imgPhoto.Width;
            int sourceHeight = imgPhoto.Height;
            int sourceX = 0;
            int sourceY = 0;
            int destX = 0;
            int destY = 0;

            float nPercent = 0;
            float nPercentW = 0;
            float nPercentH = 0;

            nPercentW = ((float)Width / (float)sourceWidth);
            nPercentH = ((float)Height / (float)sourceHeight);
            if (nPercentH < nPercentW)
            {
                nPercent = nPercentH;
                destX = System.Convert.ToInt16((Width -
                              (sourceWidth * nPercent)) / 2);
            }
            else
            {
                nPercent = nPercentW;
                destY = System.Convert.ToInt16((Height -
                              (sourceHeight * nPercent)) / 2);
            }

            int destWidth = (int)(sourceWidth * nPercent);
            int destHeight = (int)(sourceHeight * nPercent);


            Bitmap bmPhoto = new Bitmap(Width, Height, PixelFormat.Format24bppRgb);
            bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
                             imgPhoto.VerticalResolution);

            Graphics grPhoto = Graphics.FromImage(bmPhoto);
            grPhoto.Clear(Color.White);
            grPhoto.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

            grPhoto.DrawImage(imgPhoto,
                new Rectangle(destX, destY, destWidth, destHeight),
                new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
                GraphicsUnit.Pixel);

            grPhoto.Dispose();
            imgPhoto.Dispose();
            SaveHighQuality(ImageSavePath, bmPhoto);
        }

        public static void GetBiggestCrop(string ImageSavePath, int height, double aspectRatio, String ImageOpenPath)
        {

            int Height = int.Parse(height.ToString());
            int Width = Convert.ToInt32((double)Height * aspectRatio);

            Image imgPhoto = Image.FromFile(ImageOpenPath, false);

            //Determine image format
            ImageFormat fmtImageFormat = imgPhoto.RawFormat;

            //get image original width and height
            int sourceWidth = imgPhoto.Width;
            int sourceHeight = imgPhoto.Height;
            int sourceX = 0;
            int sourceY = 0;
            int destX = 0;
            int destY = 0;

            float nPercent = 0;
            float nPercentW = 0;
            float nPercentH = 0;

            nPercentW = ((float)Width / (float)sourceWidth);
            nPercentH = ((float)Height / (float)sourceHeight);

            if (nPercentH < nPercentW)
            {
                nPercent = nPercentW;
                 destY = (int)
                    ((Height - (sourceHeight * nPercent)) / 2);
            }
            else
            {
                nPercent = nPercentH;
                destX = (int)
                  ((Width - (sourceWidth * nPercent)) / 2);
            }

            int destWidth = (int)(sourceWidth * nPercent);
            int destHeight = (int)(sourceHeight * nPercent);

            Bitmap bmPhoto = new Bitmap(Width,
                    Height, PixelFormat.Format24bppRgb);
            bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
                    imgPhoto.VerticalResolution);

            Graphics grPhoto = Graphics.FromImage(bmPhoto);
            grPhoto.InterpolationMode =
                    System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

            grPhoto.DrawImage(imgPhoto,
                new Rectangle(destX, destY, destWidth, destHeight),
                new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
                GraphicsUnit.Pixel);

            grPhoto.Dispose();
            imgPhoto.Dispose();
            SaveHighQuality(ImageSavePath, bmPhoto);
        }


        public static void Resize(string ImageSavePath, int MaxHeight, int MaxWidth, String ImageOpenPath)
        {
            int intNewWidth;
            int intNewHeight;
            Image imgInput = Image.FromFile(ImageOpenPath, false);

            //Determine image format
            ImageFormat fmtImageFormat = imgInput.RawFormat;

            //get image original width and height
            int intOldWidth = imgInput.Width;
            int intOldHeight = imgInput.Height;

            //determine if to long or too high (find smallest Coef)
            double WidthCoef = MaxWidth / (double)intOldWidth;
            double HeightCoef = MaxHeight / (double)intOldHeight; ;
            double dblCoef;

            if (WidthCoef >= HeightCoef)
            {
                dblCoef = HeightCoef;
            }
            else
            {
                dblCoef = WidthCoef;
            }


            if (dblCoef < 1)
            {
                //set new width and height
                intNewWidth = Convert.ToInt32(dblCoef * intOldWidth);
                intNewHeight = Convert.ToInt32(dblCoef * intOldHeight);
            }
            else //enlarge
            {
                intNewWidth = Convert.ToInt32(intOldWidth / dblCoef);
                intNewHeight = Convert.ToInt32(intOldHeight / dblCoef);
            }
            //create new bitmap
            //            Bitmap bmpResized = new Bitmap(imgInput, intNewWidth, intNewHeight);
            Graphics thumb;
            Bitmap bmpResized = new Bitmap(intNewWidth, intNewHeight);
            thumb = Graphics.FromImage(bmpResized);
            thumb.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            thumb.DrawImage(imgInput, 0, 0, intNewWidth, intNewHeight);

            //save bitmap to disk
            SaveHighQuality(ImageSavePath, bmpResized);

            //release used resources
            imgInput.Dispose();
            bmpResized.Dispose();
        }

        public static void CropThenResize(string ImageSavePath, Rectangle Crop, int MaxWidth, int MaxHeight, String ImageOpenPath)
        {
            Image imginput = Image.FromFile(ImageOpenPath, false);

            int intNewWidth;
            int intNewHeight;

            //Determine image format
            ImageFormat fmtImageFormat = imginput.RawFormat;

            //create new bitmap 
            Bitmap bmpImage = new Bitmap(imginput);
            Bitmap cropped = bmpImage.Clone(Crop, bmpImage.PixelFormat);

            //get image original width and height
            int intOldWidth = cropped.Width;
            int intOldHeight = cropped.Height;

            //determine if to long or too high (find smallest Coef)
            double WidthCoef = MaxWidth / (double)intOldWidth;
            double HeightCoef = MaxHeight / (double)intOldHeight; ;
            double dblCoef;

            if (WidthCoef >= HeightCoef)
            {
                dblCoef = HeightCoef;
            }
            else
            {
                dblCoef = WidthCoef;
            }


            if (dblCoef < 1)
            {
                //set new width and height
                intNewWidth = Convert.ToInt32(dblCoef * intOldWidth);
                intNewHeight = Convert.ToInt32(dblCoef * intOldHeight);
            }
            else
            {
                intNewWidth = intOldWidth;
                intNewHeight = intOldHeight;
            }
            //create new bitmap
            // Bitmap bmpResized = new Bitmap(imgInput, intNewWidth, intNewHeight);
            Graphics thumb;
            Bitmap bmpResized = new Bitmap(intNewWidth, intNewHeight);
            thumb = Graphics.FromImage(bmpResized);
            thumb.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            thumb.DrawImage(cropped, 0, 0, intNewWidth, intNewHeight);

            //save bitmap to disk if 
            SaveHighQuality(ImageSavePath, bmpResized);

            //release used resources
            imginput.Dispose();
            bmpResized.Dispose();
            cropped.Dispose();
            thumb.Dispose();
        }

    }
}
